#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
#define NUM
typedef void (*func_t)();
func_t handertask[10];
void task1()
{
    printf("headertask1\n");
}
void task2()
{
    printf("headertask2\n");
}
void task3()
{
    printf("headertask3\n");
}
void task4()
{
    printf("headertask4\n");
}

void Loadtask()
{
    memset(handertask,0,sizeof(handertask));
    handertask[0] = task1;  
    handertask[1] = task2;  
    handertask[2] = task3;  
    handertask[3] = task4;  
}

int main()
{
    int count = 5;
    pid_t id = fork();
    if(id == 0)
    {   
        while(count--)
        {
            printf("This is child process, pid = %d, ppid = %d, count = %d\n",getpid(),getppid(),count);
            sleep(3);
        }
        exit(10);
    }
    else if(id > 0)
    {   
        //while(1)
        //{
        //    printf("This is parent process, pid = %d, ppid = %d\n",getpid(),getppid());
        //    sleep(1);
        //}
        Loadtask();
        int state = 0;
        while(1)
        {
            pid_t ret = waitpid(id, &state, WNOHANG);
            if(ret == 0)
            {
                printf("wait done, but child is running....\n");
                for(int i = 0; handertask[i] != NULL; i++)
                {
                    handertask[i]();
                }
            }
            else if(ret > 0)
            {
                //if(WIFEXITED(state))
                //{
                //    printf("exit code: %d", WEXITSTATUS(state));
                //}
                printf("This is parent process, wait success, ret = %d, exit code = %d, signal code = %d\n",ret,(state>>8)&0xFF,state&0x7F);
                break;
            }
            else
            {
                printf("waitpid failde.\n");
            }
            sleep(1);
        }
    }
    else
    {
        printf("fork error.\n");
    }
    
    return 0;
}
